#!/usr/bin/env python3
# _*_ coding:utf-8 _*_


# ******************************************************
# Author       : pandaZhangs
# First edited:     2024-05-24 11:24
# Last modified:	2024-05-24 11:26
# Email        : zhangs36@qq.com
# Filename     :	bpfhelper.py
# Description  : a simple script tool to transfer bpf.c
#                to skel.h for libpf 
# ******************************************************


import argparse
import subprocess
from pathlib import Path
suffix = ".c"
parser = argparse.ArgumentParser()
parser.add_argument("-n","--name",type=str,help="the ebpf kernel filename")
args = parser.parse_args()

fn = args.name

def compilUprogma(name):
    cmd =f"clang -Wall -I. -c {name}.c -o {name}.o"
    ret = subprocess.run(cmd.split(" "),stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=20,universal_newlines=True)
    if ret.returncode==0:
        return ret.stdout,None
    return  "", ret.stderr
def linker(name):
    cmd =f"clang -Wall {name}.o -L/usr/lib64 -lbpf -lelf -lz -o {name}"
    ret = subprocess.run(cmd.split(" "),stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=20)
    if ret.returncode==0:
        return None
    return   ret.stderr

def main():
    if len(fn)>0:
        p = Path(fn)
        if p.is_file() and p.name.endswith(suffix):
            n = p.name[:len(p.name)-len(suffix)]
            out,err = compilUprogma(n)
            if err is not None:
                print(err)
                return
            print(f"{fn} has been compiled!")
            err = linker(n)
            if err is not None:
                print(err)
                return
            print(f"{n} ebpf program has been linked!")
        else:
            print(f"{p.name} is invalid argument:[is file: {p.is_file()},suffix: {p.name.endswith(suffix)}]")
if __name__ == "__main__":
    main()
